package com.ruoyi.bizsys.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.enums.EnumFeeType;
import com.ruoyi.bizsys.mapper.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bizsys.service.ICustReduceOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;


/**
 * 客户减免订单记录Service业务层处理
 *
 * @author wqg
 * @date 2022-04-07
 */
@Service
public class CustReduceOrderServiceImpl extends ServiceImpl<CustReduceOrderMapper,CustReduceOrder> implements ICustReduceOrderService {

    @Autowired
    RepaymentOrderMapper repaymentOrderMapper;
    @Autowired
    CustReduceDataMapper custReduceDataMapper;
    @Autowired
    LoanOffsetMapper loanOffsetMapper;
    @Autowired
    LoanIouMapper loanIouMapper;
    @Autowired
    ReduceFeeMapper reduceFeeMapper;

    @Autowired
    AccountFlowMapper accountFlowMapper;

    /**
     * 查询客户减免订单记录
     *
     * @param id 客户减免订单记录ID
     * @return 客户减免订单记录
     */
    @Override
    public CustReduceOrder selectCustReduceOrderById(Long id) {
        return this.getById(id);
    }

    /**
     * 查询客户减免订单记录列表
     *
     * @param custReduceOrder 客户减免订单记录
     * @return 客户减免订单记录
     */
    @Override
    public List<CustReduceOrder> selectCustReduceOrderList(CustReduceOrder custReduceOrder) {
        return this.list(new QueryWrapper<>(custReduceOrder).last("order by id desc"));
    }

    /**
     * 新增客户减免订单记录
     *
     * @param custReduceOrder 客户减免订单记录
     * @return 结果
     */
    @Override
    public int insertCustReduceOrder(CustReduceOrder custReduceOrder) {
        custReduceOrder.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(custReduceOrder);
    }

    /**
     * 修改客户减免订单记录
     *
     * @param custReduceOrder 客户减免订单记录
     * @return 结果
     */
    @Override
    public int updateCustReduceOrder(CustReduceOrder custReduceOrder) {
        custReduceOrder.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(custReduceOrder);
    }

    /**
     * 批量删除客户减免订单记录
     *
     * @param ids 需要删除的客户减免订单记录ID
     * @return 结果
     */
    @Override
    public int deleteCustReduceOrderByIds(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除客户减免订单记录信息
     *
     * @param id 客户减免订单记录ID
     * @return 结果
     */
    @Override
    public int deleteCustReduceOrderById(Long id) {
        return baseMapper.deleteById(id);
    }

    /**
     * repaymentOrder更新减免订单的id 创建减免订单，状态和repayMentOrder 状态一致
     * @param custReduceOrder
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertAndupdateRorder(CustReduceOrder custReduceOrder) {
        baseMapper.insert(custReduceOrder);
        RepaymentOrder repaymentOrder =new RepaymentOrder();
        repaymentOrder.setCustReduceOrderId(custReduceOrder.getId());
        repaymentOrder.setRepaymentNo(custReduceOrder.getRepaymentNo());
        repaymentOrderMapper.updateByRepayNo(repaymentOrder);
    }

    /**
     * 优惠减免，次数+1 订单标记成功，offset减免标记成功
     * @param repaymentOrder
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAndAddReduceInfo(RepaymentOrder repaymentOrder,String actionType) {
        CustReduceOrder cdo = new CustReduceOrder();
        cdo.setId(repaymentOrder.getCustReduceOrderId());
        cdo.setStatus(repaymentOrder.getRepayStatus());
        baseMapper.updateById(cdo);
        custReduceDataMapper.updateNumAddByCustNo(repaymentOrder.getCustNo(),cdo.getId());

        ReduceFee reduceFee = new ReduceFee();
        reduceFee.setReduceSerialNo(IdUtils.reqId());

        LoanOffset loanOffset = getAndUpdateLoanOffset(repaymentOrder,actionType,reduceFee.getReduceSerialNo());

        insertReduceFee(repaymentOrder, loanOffset,reduceFee);
        updateIouReduceAmt(repaymentOrder);

        createAccountFlow(repaymentOrder, loanOffset);

    }

    /**
     * 记录账目流水
     * 减免的，判断减免是哪一项才需要单个记录
     * @param repaymentOrder
     * @param loanOffset
     */
    private void createAccountFlow(RepaymentOrder repaymentOrder, LoanOffset loanOffset) {
        AccountFlow accountFlow = new AccountFlow();
        accountFlow.setCustNo(repaymentOrder.getCustNo());
        accountFlow.setRelativeSerialNo(repaymentOrder.getCustReduceOrderId()==null?"": repaymentOrder.getCustReduceOrderId().toString());
        accountFlow.setTransferChannel(loanOffset.getActionType());
        accountFlow.setTransferTime(repaymentOrder.getCreateTime());
        accountFlow.setOffsetTime(loanOffset.getCreateTime());
        accountFlow.setDataSource("repayment_order、loan_offset");

        // 判断减免项--减免本金
        if(loanOffset.getOffsetPrincipal().compareTo(BigDecimal.ZERO)>0){
            accountFlow.setAmt(loanOffset.getOffsetPrincipal());
            accountFlow.setFeeType(EnumFeeType.OFFSET_PRINCIPAL.getCode());
            accountFlow.setId(IdWorker.getId());
            accountFlowMapper.insertByIndex(accountFlow);
        }
        // 判断减免项--减服务费
        if(loanOffset.getOffsetServiceFee().compareTo(BigDecimal.ZERO)>0){
            accountFlow.setAmt(loanOffset.getOffsetServiceFee());
            accountFlow.setFeeType(EnumFeeType.OFFSET_SERVICE_FEE.getCode());
            accountFlow.setId(IdWorker.getId());
            accountFlowMapper.insertByIndex(accountFlow);
        }
    }

    private void updateIouReduceAmt(RepaymentOrder repaymentOrder) {
        LoanIou loanIou =new LoanIou();
        loanIou.setReduceAmt(repaymentOrder.getReduceFee());
        loanIou.setLoanSerialNo(repaymentOrder.getLoanSerialNo());
        loanIouMapper.updateReduceAmt(loanIou);
    }

    private LoanOffset getAndUpdateLoanOffset(RepaymentOrder repaymentOrder,String actionType,String reduceSerialNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("repayment_no", repaymentOrder.getRepaymentNo());
        queryWrapper.eq("loan_serial_no", repaymentOrder.getLoanSerialNo());
        queryWrapper.eq("cust_no", repaymentOrder.getCustNo());
        queryWrapper.eq("action_type",actionType);
        LoanOffset loanOffset =  loanOffsetMapper.selectOne(queryWrapper);
        loanOffset.setRemissionNo(reduceSerialNo);
        loanOffset.setLoanOffsetStatus(repaymentOrder.getRepayStatus());
        loanOffsetMapper.updateById(loanOffset);
        return loanOffset;
    }

    private ReduceFee insertReduceFee(RepaymentOrder repaymentOrder, LoanOffset loanOffset,ReduceFee reduceFee) {
        reduceFee.setLoanSerialNo(repaymentOrder.getLoanSerialNo());
        reduceFee.setRepaymentNo(repaymentOrder.getRepaymentNo());
        reduceFee.setCustNo(repaymentOrder.getCustNo());
        reduceFee.setTotalAmt(repaymentOrder.getReduceFee());
        if (null!= loanOffset.getOffsetServiceFee()
                && loanOffset.getOffsetServiceFee().compareTo(BigDecimal.ZERO)!=0) {
            reduceFee.setServiceFee(loanOffset.getOffsetServiceFee());
        }
        if (null!= loanOffset.getOffsetPrincipal()
                && loanOffset.getOffsetPrincipal().compareTo(BigDecimal.ZERO)!=0) {
            reduceFee.setLoanPrincipal(loanOffset.getOffsetPrincipal());
        }
        reduceFee.setReduceSource(ReduceConfig.ACTION_TYPE_QUICK_REPAY);
        reduceFee.setReduceDesc("Qucik repay优惠减免");
        reduceFeeMapper.insert(reduceFee);
        return reduceFee;
    }

}
